package cn.spike.rockcc.web.controller;

import cn.spike.rockcc.prop.OssProp;
import cn.spike.rockcc.result.JSONResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author:spike
 * @create:2023-03-14 11:04
 */
@RestController
@RequestMapping("/oss")
public class OssSignController {

    @Autowired
    private OssProp ossProp;

    @GetMapping("/sign")
    public JSONResult sign(){
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        // 创建ossClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossProp.getEndpoint(),ossProp.getAccessId(),ossProp.getAccessKey());
        try {
            //1.给签名数据赋值
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProp.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            //2.装到容器中
            respMap.put("accessid", ossProp.getAccessId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", ossProp.getDir());
            respMap.put("host", ossProp.getHost());

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }
        return JSONResult.success(respMap);
    }
}
